document.addEventListener('DOMContentLoaded', function() {
    let isLoaded = false;
    let musicPlaying = false;
    let cakeClicked = false;
    
    // 音频元素
    const backgroundMusic = document.getElementById('background-music');
    const cakeExplosionSound = document.getElementById('cake-explosion-sound');
    const fireworksSound = document.getElementById('fireworks-sound');
    const musicToggle = document.getElementById('music-toggle');
    
    // 页面元素
    const loadingScreen = document.getElementById('loading-screen');
    const mainContent = document.getElementById('main-content');
    const birthdayCake = document.getElementById('birthday-cake');
    const navMenu = document.getElementById('nav-menu');
    const birthdayCakeContainer = document.getElementById('birthday-cake-container');

    // 初始化
    init();
    
    function init() {
        // 启动粒子系统
        if (typeof initParticles === 'function') {
            initParticles();
        }
        
        // 启动倒计时
        startCountdown();
        
        // 3秒后隐藏加载屏幕
        setTimeout(() => {
            hideLoadingScreen();
        }, 3000);
        
        // 添加事件监听器
        addEventListeners();
        
        // 添加隐藏彩蛋
        addEasterEggs();
    }
    
    function hideLoadingScreen() {
        loadingScreen.style.opacity = '0';
        loadingScreen.style.transform = 'scale(0.8)';
        
        setTimeout(() => {
            loadingScreen.classList.add('hidden');
            mainContent.classList.remove('hidden');
            isLoaded = true;
            
            // 尝试自动播放音乐
            tryAutoPlayMusic();
        }, 500);
    }
    
    function tryAutoPlayMusic() {
        const playPromise = backgroundMusic.play();
        if (playPromise !== undefined) {
            playPromise.then(() => {
                musicPlaying = true;
                musicToggle.textContent = '🎵';
                musicToggle.style.animation = 'musicPulse 2s infinite';
            }).catch(() => {
                musicPlaying = false;
                musicToggle.textContent = '🔇';
                
                // 添加用户交互启动音乐
                document.addEventListener('click', () => {
                    if (!musicPlaying) {
                        backgroundMusic.play().then(() => {
                            musicPlaying = true;
                            musicToggle.textContent = '🎵';
                            musicToggle.style.animation = 'musicPulse 2s infinite';
                        });
                    }
                }, { once: true });
            });
        }
    }
    
    function addEventListeners() {
        // 音乐控制
        musicToggle.addEventListener('click', toggleMusic);
        
        // 蛋糕点击事件
        birthdayCake.addEventListener('click', handleCakeClick);
        
        // 导航菜单点击事件
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', handleNavClick);
        });
        
        // 键盘事件
        document.addEventListener('keydown', handleKeyPress);
        
        // 触摸事件（移动端）
        addTouchEvents();
    }
    
    function toggleMusic() {
        if (musicPlaying) {
            backgroundMusic.pause();
            musicToggle.textContent = '🔇';
            musicToggle.style.animation = 'none';
            musicPlaying = false;
        } else {
            backgroundMusic.play().then(() => {
                musicToggle.textContent = '🎵';
                musicToggle.style.animation = 'musicPulse 2s infinite';
                musicPlaying = true;
            }).catch(e => {
                console.log('音乐播放失败:', e);
            });
        }
    }
    
    function handleCakeClick() {
        if (cakeClicked) return;
        cakeClicked = true;
        
        // 播放爆炸音效
        if (cakeExplosionSound) {
            cakeExplosionSound.play().catch(e => console.log('音效播放失败:', e));
        }
        
        // 蛋糕爆炸动画
        birthdayCake.style.animation = 'none';
        birthdayCake.style.transform = 'scale(1.5) rotate(360deg)';
        birthdayCake.style.opacity = '0';
        
        // 创建爆炸粒子
        createCakeExplosion();
        
        // 显示烟花
        setTimeout(() => {
            if (typeof createFireworks === 'function') {
                createFireworks();
            }
            if (fireworksSound) {
                fireworksSound.play().catch(e => console.log('烟花音效播放失败:', e));
            }
        }, 500);
        
        // 显示彩带
        setTimeout(() => {
            if (typeof createConfetti === 'function') {
                createConfetti();
            }
        }, 800);
        
        // 显示导航菜单
        setTimeout(() => {
            navMenu.classList.remove('hidden');
            birthdayCakeContainer.classList.add('hidden');

            // 隐藏蛋糕，显示新的提示文字
            document.querySelector('.subtitle').textContent = '选择你想探索的内容吧！';
            document.querySelector('.subtitle').style.animation = 'pulse 1s infinite';
        }, 1500);
    }
    
    function createCakeExplosion() {
        const cakeRect = birthdayCake.getBoundingClientRect();
        const centerX = cakeRect.left + cakeRect.width / 2;
        const centerY = cakeRect.top + cakeRect.height / 2;
        
        // 创建爆炸粒子
        for (let i = 0; i < 30; i++) {
            const particle = document.createElement('div');
            particle.style.cssText = `
                position: fixed;
                width: 8px;
                height: 8px;
                background: ${getRandomColor()};
                border-radius: 50%;
                pointer-events: none;
                z-index: 1000;
                left: ${centerX}px;
                top: ${centerY}px;
            `;
            
            document.body.appendChild(particle);
            
            // 随机方向和距离
            const angle = (Math.PI * 2 * i) / 30;
            const distance = 100 + Math.random() * 200;
            const endX = centerX + Math.cos(angle) * distance;
            const endY = centerY + Math.sin(angle) * distance;
            
            // 动画
            particle.animate([
                { 
                    transform: 'translate(0, 0) scale(1)',
                    opacity: 1
                },
                { 
                    transform: `translate(${endX - centerX}px, ${endY - centerY}px) scale(0)`,
                    opacity: 0
                }
            ], {
                duration: 1000 + Math.random() * 500,
                easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'
            }).onfinish = () => {
                particle.remove();
            };
        }
    }
    
    function getRandomColor() {
        const colors = ['#ff6b9d', '#4ecdc4', '#ffe66d', '#ff8a80', '#82b1ff', '#b388ff'];
        return colors[Math.floor(Math.random() * colors.length)];
    }
    
    function handleNavClick(e) {
        const page = e.currentTarget.dataset.page;
        if (page) {
            // 添加点击效果
            e.currentTarget.style.transform = 'scale(0.95)';
            setTimeout(() => {
                e.currentTarget.style.transform = '';
            }, 150);
            
            // 页面跳转延迟，增加体验感
            setTimeout(() => {
                window.location.href = `${page}.html`;
            }, 300);
        }
    }
    
    function startCountdown() {
        // 设置目标日期（2025年8月15日）
        const targetDate = new Date('2025-12-09T00:00:00').getTime();
        
        function updateCountdown() {
            const now = new Date().getTime();
            const distance = targetDate - now;
            
            if (distance > 0) {
                const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((distance % (1000 * 60)) / 1000);
                
                document.getElementById('days').textContent = days.toString().padStart(2, '0');
                document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
                document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
                document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');
            } else {
                // 生日到了！
                document.querySelector('.countdown-title').textContent = '🎉 生日快乐！🎉';
                document.getElementById('days').textContent = '00';
                document.getElementById('hours').textContent = '00';
                document.getElementById('minutes').textContent = '00';
                document.getElementById('seconds').textContent = '00';
            }
        }
        
        updateCountdown();
        setInterval(updateCountdown, 1000);
    }
    
    function handleKeyPress(e) {
        switch(e.key) {
            case ' ':
                e.preventDefault();
                if (!cakeClicked) {
                    handleCakeClick();
                } else {
                    toggleMusic();
                }
                break;
            case 'Enter':
                if (!cakeClicked) {
                    handleCakeClick();
                }
                break;
            case 'Escape':
                // 隐藏彩蛋：按ESC键触发特殊效果
                createSpecialEffect();
                break;
        }
    }
    
    function addTouchEvents() {
        let touchStartTime = 0;
        let touchCount = 0;
        
        document.addEventListener('touchstart', (e) => {
            touchStartTime = Date.now();
        });
        
        document.addEventListener('touchend', (e) => {
            const touchDuration = Date.now() - touchStartTime;
            
            // 长按效果
            if (touchDuration > 1000) {
                createSpecialEffect();
            }
        });
        
        // 多点触控
        document.addEventListener('touchstart', (e) => {
            if (e.touches.length >= 3) {
                createSpecialEffect();
            }
        });
    }
    
    function addEasterEggs() {
        let clickCount = 0;
        let clickTimer = null;
        
        // 连续点击皇冠的彩蛋
        document.querySelector('.birthday-crown').addEventListener('click', () => {
            clickCount++;
            
            if (clickTimer) {
                clearTimeout(clickTimer);
            }
            
            clickTimer = setTimeout(() => {
                if (clickCount >= 5) {
                    // 触发隐藏效果
                    createRainbowEffect();
                }
                clickCount = 0;
            }, 2000);
        });
        
        // 鼠标轨迹彩蛋
        let mouseTrail = [];
        document.addEventListener('mousemove', (e) => {
            mouseTrail.push({ x: e.clientX, y: e.clientY, time: Date.now() });
            
            // 保持轨迹长度
            if (mouseTrail.length > 50) {
                mouseTrail.shift();
            }
            
            // 检测特殊轨迹（比如画圆）
            if (mouseTrail.length === 50) {
                if (isCircularMotion(mouseTrail)) {
                    createSpecialEffect();
                    mouseTrail = [];
                }
            }
        });
    }
    
    function isCircularMotion(trail) {
        // 简单的圆形轨迹检测
        if (trail.length < 20) return false;
        
        const centerX = trail.reduce((sum, p) => sum + p.x, 0) / trail.length;
        const centerY = trail.reduce((sum, p) => sum + p.y, 0) / trail.length;
        
        let radiusSum = 0;
        for (let point of trail) {
            const distance = Math.sqrt(Math.pow(point.x - centerX, 2) + Math.pow(point.y - centerY, 2));
            radiusSum += distance;
        }
        
        const avgRadius = radiusSum / trail.length;
        let variance = 0;
        
        for (let point of trail) {
            const distance = Math.sqrt(Math.pow(point.x - centerX, 2) + Math.pow(point.y - centerY, 2));
            variance += Math.pow(distance - avgRadius, 2);
        }
        
        variance /= trail.length;
        
        // 如果方差小于某个阈值，认为是圆形轨迹
        return variance < 1000 && avgRadius > 50;
    }
    
    function createSpecialEffect() {
        // 创建特殊的粒子爆炸效果
        const colors = ['#ff6b9d', '#4ecdc4', '#ffe66d', '#ff8a80', '#82b1ff', '#b388ff'];
        
        for (let i = 0; i < 100; i++) {
            const particle = document.createElement('div');
            particle.style.cssText = `
                position: fixed;
                width: 6px;
                height: 6px;
                background: ${colors[Math.floor(Math.random() * colors.length)]};
                border-radius: 50%;
                pointer-events: none;
                z-index: 1000;
                left: ${Math.random() * window.innerWidth}px;
                top: ${Math.random() * window.innerHeight}px;
            `;
            
            document.body.appendChild(particle);
            
            particle.animate([
                { 
                    transform: 'scale(0) rotate(0deg)',
                    opacity: 0
                },
                { 
                    transform: 'scale(1) rotate(180deg)',
                    opacity: 1
                },
                { 
                    transform: 'scale(0) rotate(360deg)',
                    opacity: 0
                }
            ], {
                duration: 2000,
                easing: 'ease-out'
            }).onfinish = () => {
                particle.remove();
            };
        }
    }
    
    function createRainbowEffect() {
        // 彩虹效果
        const rainbow = document.createElement('div');
        rainbow.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(45deg, 
                red, orange, yellow, green, blue, indigo, violet);
            opacity: 0.3;
            pointer-events: none;
            z-index: 999;
        `;
        
        document.body.appendChild(rainbow);
        
        rainbow.animate([
            { opacity: 0 },
            { opacity: 0.3 },
            { opacity: 0 }
        ], {
            duration: 3000,
            easing: 'ease-in-out'
        }).onfinish = () => {
            rainbow.remove();
        };
    }
    
    // 页面可见性变化时的处理
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            if (musicPlaying) {
                backgroundMusic.pause();
            }
        } else {
            if (musicPlaying) {
                backgroundMusic.play().catch(e => console.log('恢复播放失败:', e));
            }
        }
    });
    
    // 错误处理
    window.addEventListener('error', (e) => {
        console.log('页面错误:', e.error);
    });
    
    console.log('欢迎页面已加载完成！');
    console.log('隐藏彩蛋提示：');
    console.log('1. 连续点击皇冠5次');
    console.log('2. 按ESC键');
    console.log('3. 用鼠标画圆');
    console.log('4. 三指触摸（移动端）');
    console.log('5. 长按屏幕（移动端）');
});

